package cc.rome753.wat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.core.content.ContextCompat;

import java.util.List;

public class PermissionUtil {

    public static final String[] mediaPerms = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};

    public static final boolean isMediaPermissionsGranted(Context context) {
        for (String per : mediaPerms) {
            if (!isPermissionGranted(context, per)) {
                return false;
            }
        }
        return true;
    }

    public static final boolean isPermissionsGranted(Context context, List<String> permissions) {
        for (String per : permissions) {
            if (!isPermissionGranted(context, per)) {
                return false;
            }
        }
        return true;
    }

    public static final boolean isPermissionGranted(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission)
        == PackageManager.PERMISSION_GRANTED;
    }

    public static void gotoSettings(Context context, boolean show) {
        if (!show) {
            gotoSettings(context);
        } else {
            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle("请授予相应权限")
                    .setMessage("如果要正常运行该程序，需要授予摄像头权限和录音权限。请授权！")
                    .setNegativeButton("不授权", null)
                    .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            gotoSettings(context);
                            dialog.dismiss();
                        }
                    }).create();
            dialog.show();
        }
    }

    public static void gotoSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }
}
